/* eslint-disable array-callback-return */
import React from 'react';
import { CloseOutlined, UploadOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Input,
  Select,
  message,
  Row,
  Col,
  Tabs,
  Spin,
  Upload,
  AutoComplete,
  Modal,
} from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import HOCSelect from '@/components/AntDesign/Select';
import downloadFile, { urlParse, requestHeadersMd5 } from '@/utils/utils';
import styles from '@/utils/utils.less';
import Invoice from './Update/Invoice';
import MailingAddress from './Update/MailingAddress';
import Bank from './Update/Bank';
import Contact from './Update/Contact';
import Costcenter from './Update/CostCenter';

const { Option } = Select;
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { Search } = Input;

@connect(({ login, loading, customer }) => ({
  login,
  loading: loading.effects['custedit/getAreaList'] ? false : loading.models.custedit,
  isRequired: customer.isRequired,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      custId: '',
      tabList: [],
      activeKey: '1',
      comTypeList: [],
      industryCodeList: [],
      taxerTypeList: [],
      genderList: [],
      hasChildList: [],
      uploadUrl: '/csApi/fileServer/uploadFile',
      downloadUrl: '/csApi/fileServer/downloadFile',
      custAffixList: [],
      oldFileList: [],
      oldFileListleng: null,
      custAffixListleng: null,
      custServiceList: [], // 负责人.
      invTypeList: [],
      company: true, // 是否是本公司
      supplyList: [],
      custList: [],
    };
  }

  componentDidMount() {
    const { location, form, dispatch } = this.props;
    let { custId, activeKey } = this.state;
    custId = urlParse(location.search).custId ? urlParse(location.search).custId : custId;
    activeKey = urlParse(location.search).activeKey
      ? urlParse(location.search).activeKey
      : activeKey;

    // 获取供应商名称列表数据
    dispatch({
      type: 'customer/getListByUser',
      payload: {
        name: null,
        status: 2,
      },
    }).then(response => {
      if (response.success && response.data) {
        this.setState({ supplyList: response.data });
      } else {
        this.setState({ supplyList: [] });
      }
    });

    if (custId) {
      dispatch({
        type: 'custedit/getBasciInfo',
        payload: { custId },
      }).then(res => {
        if (res.success && res.data) {
          this.setState({ custId, activeKey });
          this.getDictList();
          const getFieldsList = form.getFieldsValue();
          Object.keys(res.data).forEach(key => {
            if (res.data[key]) {
              if (key === 'corpNature' || key === 'industryCode' || key === 'idType') {
                res.data[key] = `${res.data[key]}`;
              }
            }
          });
          Object.keys(getFieldsList).forEach(key => {
            if (res.data[key]) {
              if (key === 'corpNature' || key === 'industryCode' || key === 'idType') {
                form.setFieldsValue({ [key]: { key: res.data[key] } });
              } else {
                form.setFieldsValue({ [key]: res.data[key] });
              }
            }
          });
          if (res.data.custAffixList && res.data.custAffixList.length) {
            this.setState({ oldFileList: res.data.custAffixList });
          }
          // 获取当前角色所在公司对应的平台供应商
          dispatch({
            type: 'customer/plasuppList',
            payload: {},
          }).then(responses => {
            if (res.data.suppId === responses.data[0].suppId) {
              this.setState({
                company: true,
              });
              dispatch({
                type: 'customer/updateModelData',
                payload: { isRequired: true },
              });
            } else {
              this.setState({
                company: false,
              });
              dispatch({
                type: 'customer/updateModelData',
                payload: { isRequired: false },
              });
            }
          });
        } else {
          message.warning(`${res.message || '暂无数据！'}`);
        }
      });
      dispatch({
        type: 'custedit/fetchRespUserList',
        payload: {},
      }).then(res => {
        if (res.success && res.data) {
          res.data.map(item => {
            const temp = item;
            temp.userName = `${item.orgName}-${item.userName}`;
          });
          this.setState({
            custServiceList: res.data,
          });
        } else {
          this.setState({ custServiceList: [] });
        }
      });
    } else {
      router.goBack();
    }
  }

  // 获取字典:
  // 当前页签CUST_TAB、公司性质CORP_NATURE、行业分类INDST_CODE、证件类型CUST_ID_TYPE、纳税人类型、所属银行BANK_ID、性别GENDER、是否有小孩HAS_CHILD、
  getDictList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: [
        'CUST_TAB',
        'CORP_NATURE',
        'INDST_CODE',
        'CUST_ID_TYPE',
        'TAXPAYER_TYPE',
        'BANK_ID',
        'GENDER',
        'HAS_CHILD',
        'MINI_INV_TYPE',
      ],
    }).then(dictCode => {
      if (dictCode) {
        const sortNumber = (a, b) => a.itemCode - b.itemCode;
        dictCode.CUST_TAB.sort(sortNumber);
        this.setState({
          tabList: dictCode.CUST_TAB,
          comTypeList: dictCode.CORP_NATURE,
          industryCodeList: dictCode.INDST_CODE,
          taxerTypeList: dictCode.TAXPAYER_TYPE,
          bankList: dictCode.BANK_ID,
          genderList: dictCode.GENDER,
          hasChildList: dictCode.HAS_CHILD,
          invTypeList: dictCode.MINI_INV_TYPE,
        });
      }
    });
  };

  // 搜索客户:主数据接口
  searchCust = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'custedit/searchCust',
      payload: { name: value },
    }).then(res => {
      if (res.success && res.data) {
        this.setState({
          custList: res.data,
        });
      } else {
        this.setState({ custList: [] });
      }
    });
  };

  // 切换页签
  changeTabPane = activeKey => {
    const { custId } = this.state;
    this.setState({ activeKey });
    router.push(`/salemanage/customer/update?custId=${custId}&activeKey=${activeKey}`);
  };

  // 文件上传
  changeUpload = (info, listContFile, getFieldName) => {
    const { form } = this.props;
    const { custAffixList, custAffixListleng, oldFileListleng, oldFileList } = this.state;
    if (custAffixListleng > 4 || oldFileListleng > 4) {
      this.setState({
        oldFileListleng: oldFileList.length,
        custAffixListleng: custAffixList.length,
      });
    } else {
      const { file, fileList } = info;
      const { downloadUrl } = this.state;
      const newData = listContFile.map(item => ({ ...item }));
      if (file.status === 'done' && file.response.success) {
        const fileId = file.response.data.split('|')[0];
        const fileName = file.response.data.split('|')[1];
        fileList.map(files => {
          const temp = files;
          temp.url = `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`;
          temp.linkProps = { download: `${fileName}` };
        });
        newData.push({
          uid: file.uid,
          custAffixId: fileId,
          affixName: fileName,
        });
        form.setFieldsValue({ [getFieldName]: newData });
        this.setState({ [getFieldName]: newData });
        message.success('文件上传成功！');
      }
      if ((file.status === 'done' && !file.response.success) || file.status === 'error') {
        message.error('上传失败！');
      }
      this.setState({
        oldFileListleng: oldFileList.length,
        custAffixListleng: custAffixList.length,
      });
    }
  };

  // 移除文件
  removeFile = (file, custAffixList) => {
    const newData = custAffixList.filter(item => item.uid !== file.uid);
    this.setState({ custAffixList: newData });
  };

  // 删除页面素材文件
  delFile = (id, oldFileList) => {
    const newData = oldFileList.filter(item => item.custAffixId !== id);
    this.setState({ oldFileList: newData });
  };

  // 提交
  sumSubmit = e => {
    e.preventDefault();
    const { form, dispatch } = this.props;
    const { custId, oldFileList, custAffixList } = this.state;
    const data = {};
    let submitData = {};
    form.validateFieldsAndScroll((error, values) => {
      if (!error) {
        const obj = values;
        Object.keys(values).forEach(key => {
          if (values[key] && values[key].key) {
            data[key] = values[key].key;
          } else {
            data[key] = values[key] ? values[key] : '';
          }
        });
        delete obj.custAffixList;
        if (oldFileList.length) {
          oldFileList.map(f => {
            const ff = f;
            delete ff.custId;
            delete ff.affixType;
            delete ff.glInfoId;
          });
        }
        if (custAffixList.length) {
          custAffixList.map(f => {
            const objValue = f;
            delete objValue.uid;
          });
        }
        const newCustAffixList = custAffixList.concat(oldFileList);
        submitData = { ...data, custId, custAffixList: newCustAffixList, name: values.name };
        if(values.fmNcNo!==null){
          dispatch({
            type: 'custedit/checkSubmit',
            payload: submitData,
          }).then(response => {
            if (response.success) {
              if (response.data && response.data.message) {
                Modal.confirm({
                  title: '请注意！',
                  content: `${response.data.message}`,
                  okText: '继续提交',
                  cancelText: '返回修改',
                  icon: <ExclamationCircleOutlined />,
                  onOk: () => {
                    dispatch({
                      type: 'custedit/submit',
                      payload: submitData,
                    }).then(res => {
                      if (res.success) {
                        message.success(`${res.message || '修改成功！'}`, 1, () => {
                          router.goBack();
                        });
                      } else {
                        message.warning(`${res.message || '修改失败！'}`);
                      }
                    });
                  },
                });
              } else {
                dispatch({
                  type: 'custedit/submit',
                  payload: submitData,
                }).then(res => {
                  if (res.success) {
                    message.success(`${res.message || '修改成功！'}`, 1, () => {
                      router.goBack();
                    });
                  } else {
                    message.warning(`${res.message || '修改失败！'}`);
                  }
                });
              }
            } else {
              message.warning(`${response.message || '修改检验失败！'}`);
            }
          });
        }else{
          dispatch({
            type: 'custedit/submit',
            payload: submitData,
          }).then(res => {
            if (res.success) {
              message.success(`${res.message || '修改成功！'}`, 1, () => {
                router.goBack();
              });
            } else {
              message.warning(`${res.message || '修改失败！'}`);
            }
          });
        }
      }
    });
  };

  render() {
    const {
      custId,
      taxerTypeList,
      bankList,
      genderList,
      hasChildList,
      uploadUrl,
      custAffixList,
      oldFileList,
      custServiceList,
      invTypeList,
      comTypeList,
      industryCodeList,
      oldFileListleng,
      custAffixListleng,
      activeKey,
      tabList,
      company,
      supplyList,
      custList,
    } = this.state;
    const {
      form: { getFieldDecorator },
      loading,
      isRequired,
    } = this.props;
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    // 下拉选项
    // 公司类型
    const comTypeOL =
      comTypeList &&
      comTypeList.length &&
      comTypeList.map(options => <Option key={options.itemCode}>{options.itemName}</Option>);
    // 行业分类
    const industryCodeOL =
      industryCodeList &&
      industryCodeList.length &&
      industryCodeList.map(options => <Option key={options.itemCode}>{options.itemName}</Option>);

    // 客户名称的列表
    const custOptions = custList.map(opt => (
      // <Option key={opt.mdCustId} value={opt.mdCustId}>
      <Option key={opt.name} value={opt.name}>
        {opt.name}
      </Option>
    ));

    // 文件上传

    const uploadProps = {
      action: uploadUrl,
      headers: requestHeadersMd5(),
      onChange: info => this.changeUpload(info, custAffixList, 'custAffixList'),
      onRemove: file => this.removeFile(file, custAffixList),
    };
    const BasicInfo = (
      <Spin tip="Loading..." spinning={loading}>
        <Form layout="vertical">
          <Row gutter={64}>
            <Col {...colProps}>
              <FormItem label="签约方">
                {getFieldDecorator('suppId', {
                  rules: [{ required: true, message: '请输入' }],
                })(
                  <HOCSelect
                    placeholder="请选择"
                    // onChange={e => isCompany(e)}
                    showSearch
                    optionFilterProp="children"
                    disabled
                  >
                    {supplyList.map(one => (
                      <Option key={one.suppId} value={one.suppId}>
                        {one.name}
                      </Option>
                    ))}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="客户名称">
                {getFieldDecorator('name', {
                  rules: [{ required: true, message: '请输入' }],
                  initialValue: '默认测试数据',
                })(
                  <AutoComplete dataSource={custOptions}>
                    <Search
                      placeholder="请输入关键字检索"
                      maxLength={100}
                      onSearch={value => this.searchCust(value)}
                    />
                  </AutoComplete>
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="统一社会信用代码">
                {getFieldDecorator('uniCreditCode', {
                  rules: [
                    {
                      required: true,
                      message: '18位的数字与字母组合',
                      max: 18,
                      pattern: /^[A-Za-z0-9]{1,18}$/,
                    },
                  ],
                })(<Input placeholder="请准确输入18位统一社会信用代码" disabled />)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={64}>
            <Col {...colProps}>
              <FormItem label="客户编号">
                {getFieldDecorator('no', {
                  rules: [{ required: true, message: '请输入' }],
                  initialValue: '默认测试数据',
                })(<Input placeholder="请输入" disabled />)}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="公司类型">
                {getFieldDecorator('corpNature', {
                  rules: [{ required: true, message: '请选择' }],
                })(
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    style={{ width: '100%' }}
                    allowClear
                    labelInValue
                    showSearch
                    optionFilterProp="children"
                  >
                    {comTypeOL}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="行业分类">
                {getFieldDecorator('industryCode', {
                  rules: [{ required: true, message: '请选择' }],
                })(
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    style={{ width: '100%' }}
                    allowClear
                    labelInValue
                    showSearch
                    optionFilterProp="children"
                    // disabled
                  >
                    {industryCodeOL}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={64}>
            <Col {...colProps}>
              <FormItem label="财务NC编码">
                {getFieldDecorator('fmNcNo', {
                  rules: [
                    {
                      // required: isRequired,
                      message: '请输入不超过15位的纯数字',
                      pattern: /^\d{1,15}$/,
                    },
                  ],
                })(<Input placeholder="请输入" maxLength={15} />)}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="办公地址">
                {getFieldDecorator('detailAddress', {})(
                  <Input placeholder="请输入" maxLength={100} />
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="工作邮箱">
                {getFieldDecorator('email', {
                  rules: [{ type: 'email', message: '应为邮箱格式' }],
                })(<Input placeholder="请输入" maxLength={50} />)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={64}>
            <Col {...colProps}>
              <FormItem label="负责人">
                {getFieldDecorator('primId', {
                  rules: [{ required: true, message: '请选择' }],
                })(
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    style={{ width: '100%' }}
                    showSearch
                    optionFilterProp="children"
                    disabled
                  >
                    {custServiceList.map(options => (
                      <Option key={options.userId}>{options.userName}</Option>
                    ))}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="创建人">
                {getFieldDecorator('creName')(
                  <Input placeholder="请输入" maxLength={200} disabled />
                )}
              </FormItem>
            </Col>
            <Col {...colProps}>
              <FormItem label="备注">
                {getFieldDecorator('remark', {})(<Input placeholder="请输入" maxLength={200} />)}
              </FormItem>
            </Col>
          </Row>

          <Row style={{ width: '100%' }}>
            <Row style={{ fontWeight: 'bold', marginBottom: 10, width: '100%' }}>基本信息附件</Row>
            {oldFileList && oldFileList.length ? (
              <Row style={{ width: '100%' }}>
                {oldFileList.map(item => (
                  <Col key={item.custAffixId} style={{ marginBottom: 10 }}>
                    <a
                      onClick={e => {
                        e.preventDefault();
                        downloadFile({ fileId: item.custAffixId, fileName: item.affixName });
                      }}
                    >
                      {item.affixName}
                    </a>
                    <CloseOutlined
                      style={{
                        marginLeft: 30,
                        lineHeight: '20px',
                        color: '#40a9ff',
                        fontSize: '12px',
                      }}
                      onClick={() => this.delFile(item.custAffixId, oldFileList)}
                    />
                  </Col>
                ))}
              </Row>
            ) : null}
            <Row>
              <Form.Item>
                {getFieldDecorator('custAffixList', {
                  rules: [{ required: false, message: '请输入' }],
                })(
                  <Upload {...uploadProps}>
                    {oldFileListleng > 4 || custAffixListleng > 4 ? null : (
                      <Button>
                        <UploadOutlined /> 上传附件
                      </Button>
                    )}
                  </Upload>
                )}
              </Form.Item>
            </Row>
          </Row>
        </Form>
        <div
          style={{
            paddingTop: 24,
            marginBottom: 16,
            textAlign: 'right',
            boxShadow: '0 -1px 2px rgba(0, 0, 0, 0.03)',
            borderTop: '1px solid #e8e8e8',
          }}
        >
          <Button onClick={() => router.goBack()} style={{ marginRight: 10 }}>
            取消
          </Button>
          <Button type="primary" onClick={this.sumSubmit}>
            提交
          </Button>
        </div>
      </Spin>
    );
    // 获取页签组件
    const getTabPane = key => {
      switch (key) {
        case '1':
          return BasicInfo;
        case '2':
          return (
            <Invoice custId={custId} taxerTypeList={taxerTypeList} invTypeList={invTypeList} />
          );
        case '3':
          return <MailingAddress custId={custId} />;
        case '4':
          return <Bank custId={custId} bankList={bankList} />;
        case '5':
          return <Contact custId={custId} genderList={genderList} hasChildList={hasChildList} />;
        case '6':
          return <Costcenter custId={custId} />;
        default:
          return <div />;
      }
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.tabCard}>
          <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
            {company ? (
              tabList.length &&
              tabList.map(pane => (
                <TabPane tab={pane.itemName} key={pane.itemCode}>
                  {getTabPane(pane.itemCode)}
                </TabPane>
              ))
            ) : (
              <TabPane
                tab={tabList.length && tabList[0].itemName}
                key={tabList.length && tabList[0].itemCode}
              >
                {getTabPane(tabList.length && tabList[0].itemCode)}
              </TabPane>
            )}
          </Tabs>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
